<template>
  <div>
    <div class="ele-body">
      <div class="ele-bg-white">
        <div class="padding-15">
          <a-row style="margin: 0 0 30px">
            <a-col :span="8">
              <span>角色名称</span>
              <span class="margin-left-15">{{ infos.name }}</span>
            </a-col>
            <a-col :span="8">
              <span>角色描述</span>
              <span class="margin-left-15">{{ infos.description }}</span>
            </a-col>
          </a-row>
          <div class="solid-bottom">
            <a-space size="middle" style="border-bottom: 1px solid #d9d9d9">
              <a-radio-group v-model:value="changeValue">
                <a-radio-button value="1">权限设置</a-radio-button>
                <!-- <a-radio-button value="0">门店权限</a-radio-button> -->
              </a-radio-group>
            </a-space>
          </div>
          <div>
            <div class="flex">
              <div>
                <div class="tit_wrap">
                  <div class="flex align-center">
                    <div
                      class="flex1 top_tit_item"
                      :class="{ active: topCurrent == 0 }"
                      @click="topToggle(0)"
                      >后台权限</div
                    >
                    <div
                      class="flex1 top_tit_item"
                      :class="{ active: topCurrent == 1 }"
                      @click="topToggle(1)"
                      >APP权限</div
                    >
                  </div>

                  <div
                    class="tit_item"
                    :class="{ active: current == index }"
                    v-for="(item, index) in options"
                    :key="index"
                    @click="toggle(item, index)"
                  >
                    {{ item.title }}
                  </div>
                </div>
                <a-space class="margin-top-30">
                  <a-button type="primary" class="ele-btn-icon" @click="save()"
                    ><span>确定</span></a-button
                  >
                </a-space>
              </div>
              <div class="flex1 margin-15">
                <a-tree
                  v-model:selectedKeys="selectedKeys"
                  v-model:checkedKeys="checkedKeys"
                  default-expand-all
                  checkable
                  @check="check"
                  :tree-data="treeData"
                >
                  <template #title="{ title, key }">
                    {{ key }}
                    <span v-if="key === '0-0-1-0'" style="color: #1890ff">{{
                      title
                    }}</span>
                    <span v-else>{{ title }}</span>
                  </template>
                </a-tree>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, unref, onMounted } from 'vue';
  import { message } from 'ant-design-vue';
  import zbTable from '@/components/zbTable/index.vue';
  import {
    PlusOutlined,
    UploadOutlined,
    ClearOutlined,
    RestOutlined
  } from '@ant-design/icons-vue';
  import { actionFn } from '@/utils/action.js';
  import { useRouter } from 'vue-router';
  import {
    detail,
    get_parent,
    get_menu,
    get_permission,
    set_permission
  } from '@/api/user/role';

  const { currentRoute } = useRouter();
  const { query } = unref(currentRoute);
  const loading = ref(false);
  const infos = ref({});

  const changeValue = ref('1');
  const selectedKeys = ref([]);
  const checkedKeys = ref([]);
  const treeData = ref([]); //树状图数据
  const arr = ref([]);

  const form = reactive({
    columns: 'menu',
    pid: '',
    cate: '1',
    role_id: ''
  });
  const form2 = reactive({
    permissions: [],
    guard: 'backend',
    role_id: '',
    pid: '',
    cate: ''
  });

  const current = ref(0);
  const options = ref([]);
  const topCurrent = ref(0);

  onMounted(() => {
    form.role_id = query.id;
    form2.role_id = query.id;
    detail({ role_id: query.id })
      .then(async (res) => {
        infos.value = res;
      })
      .catch((e) => {
        message.error(e.message || e);
      });
    get_parent()
      .then(async (res) => {
        options.value = res;
        if (options.value.length > 0) {
          form.pid = options.value[0].id;
        }
        getMenu();
      })
      .catch((e) => {
        message.error(e.message || e);
      });
  });
  const menuList = ref([]);
  const menuIdArr = ref([]);
  const getMenu = async () => {
    loading.value = true;
    selectedKeys.value = [];
    checkedKeys.value = [];
    treeData.value = [];
    menuList.value = [];
    menuIdArr.value = [];
    await get_menu(form)
      .then((res) => {
        menuList.value = res;
      })
      .catch((e) => {
        message.error(e.message || e);
      });

    await get_permission({ role_id: form2.role_id, guard: form2.guard })
      .then((res) => {
        menuIdArr.value = res.select_ids;

        const dealTreeData = (menuList) => {
          const data = menuList.map((item) => ({
            key: item.id,
            title: item.title,
            children:
              item.child && item.child.length ? dealTreeData(item.child) : null
          }));
          return data;
        };
        treeData.value = dealTreeData(menuList.value);
        // 回显数据转换
        function menuId(arr, menuArr, result = []) {
          arr.find((item) => {
            if (menuArr.includes(item.key) && !item.children) {
              result.push(item.key);
            }
            if (item.children) menuId(item.children, menuArr, result);
          });
          return result;
        }
        checkedKeys.value = menuId(treeData.value, menuIdArr.value);
        console.log('checkedKeys', checkedKeys.value);
        loading.value = false;
      })
      .catch((e) => {
        message.error(e.message || e);
      });
  };

  //树状图选择
  const check = (checkedKeys, info) => {
    selectedKeys.value = checkedKeys.concat(info.halfCheckedKeys);
    arr.value = arr.value.concat(checkedKeys);
	console.log('info', info.halfCheckedKeys);
	console.log('arr.value', arr.value);
  };
  const save = () => {
    console.log('arr.value', arr.value);
    form2.permissions = selectedKeys.value;
		form2.permissions.push(form.pid);
    form2.pid = form.pid;
    form2.cate = form.cate;
		console.log('form2', form2);
    set_permission(form2)
      .then((res) => {
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e.message || e);
      });
  };

  //切换是后台权限， 还是app权限
  const topToggle = (index) => {
    topCurrent.value = index;
    if (index == 0) {
      form2.guard = 'backend';
    }
    if (index == 1) {
      form2.guard = 'frontend';
    }
  };
  const changeToggle = (e) => {
    console.log(e);
    form.cate = e.target.value;
    getMenu();
  };
  const toggle = (item, index) => {
    current.value = index;
    if (topCurrent.value == 0) {
      form.pid = item.id;
      getMenu();
    }
    if (topCurrent.value == 1) {
    }
  };
</script>

<style lang="less" scoped>
  .ant-radio-button-wrapper {
    padding: 0 22px;
  }
  .tit_wrap {
    margin: 6px 0 0 0;
    height: auto;
  }
  .tit_item {
    text-align: center;
  }
</style>
